package com.liujit.feign.config;

import feign.Feign;
import lombok.Data;
import okhttp3.ConnectionPool;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

/**
 * @author: liujun
 * @date: 2021/6/21 1:52 下午
 * @description: 配置okhttp与连接池，ConnectionPool默认创建5个线程，保持5分钟长连接
 */
@Data
@Configuration
@ConditionalOnClass(Feign.class)
@AutoConfigureBefore(FeignAutoConfiguration.class)
@ConfigurationProperties(prefix = "okhttp")
public class OkHttpConfig {

    /**
     * 连接超时
     */
    private String connectTimeout;

    /**
     * 读超时
     */
    private String readTimeout;

    /**
     * 写超时
     */
    private String writeTimeout;

    /**
     * 线程数
     */
    private String maxIdleConnections;

    /**
     * 保持长链接时间
     */
    private String keepAliveDuration;

    @Bean
    public okhttp3.OkHttpClient okHttpClient() {
        return new okhttp3.OkHttpClient.Builder()
                //设置连接超时
                .connectTimeout(Integer.valueOf(connectTimeout), TimeUnit.SECONDS)
                //设置读超时
                .readTimeout(Integer.valueOf(readTimeout), TimeUnit.SECONDS)
                //设置写超时
                .writeTimeout(Integer.valueOf(writeTimeout), TimeUnit.SECONDS)
                //是否自动重连
                .retryOnConnectionFailure(true).connectionPool(
                        new ConnectionPool(Integer.valueOf(maxIdleConnections), Long.valueOf(keepAliveDuration),
                                TimeUnit.MINUTES)).build();
    }
}
